<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>The Ajax 02 Page</h1>
    <button onclick="doAjaxGet()">doGet</button>
    <button onclick="doAjaxPost()">doPost</button>
    <button onclick="doAjaxDelete()">doDelete</button>
    <button onclick="doAjaxPut()">doPut</button>

    <!--服务器返回结果更现在下方-->
    <div id="result">
    </div>

    <script type="text/javascript">
        function doAjaxGet() {
            let xhr = new XMLHttpRequest();

            xhr.onreadystatechange = function () {
                if(xhr.readyState == 4 && xhr.status == 200){
                    document.getElementById("result").innerHTML = xhr.responseText;
                }
            }
            // get方法传数据, 要在url后加 ?name=aaa的形式传递
            xhr.open("GET", "http://localhost/doAjaxGet", true);
            xhr.send(null);
        }

        function doAjaxPost() {
            let xhr = new XMLHttpRequest();

            xhr.onreadystatechange = function () {
                if(xhr.readyState == 4 && xhr.status == 200){
                    document.getElementById("result").innerHTML = xhr.responseText;
                }
            }

            //POST传递值的时候, 必须要设置请求头(必须在open函数之后)
            xhr.open("POST", "http://localhost/doAjaxPost", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            //Post方法传递数据, 需要按照一定的格式来作为send方法的参数
            xhr.send("id=12&name=电脑&remark=双11最低五折");
        }

        function doAjaxDelete() {
            let xhr = new XMLHttpRequest();
            debugger;
            xhr.onreadystatechange = function () {
                if(xhr.readyState == 4 && xhr.status == 200){
                    document.getElementById("result").innerHTML = xhr.responseText;
                }
            }

            alert("进来");
            //下面的get方法也可以改为delete方法
            xhr.open("DELETE","http://localhost/doAjaxDelete?id=100",true);
            xhr.send(null);
        }

        function doAjaxPut() {
            let xhr = new XMLHttpRequest();

            xhr.onreadystatechange = function () {
                if(xhr.readyState == 4 && xhr.status == 200){
                    document.getElementById("result").innerHTML = xhr.responseText;
                }
            }

            xhr.open("PUT", "http://localhost/doAjaxUpdate?id=12&name=华为&remark=麒麟970", true);
            xhr.send(null);
        }



    </script>

</body>
</html>